/*
 * @Author: tanhongzhao cdtanhongzhao@jd.com
 * @Date: 2023-07-05 14:14:18
 * @LastEditors: cdtangxiejun
 * @LastEditTime: 2024-03-07 11:22:45
 * @FilePath: /cone-service/middleware/index.js
 * @Description:
 *
 */
const xssmw = require("./xssmw");
const userAgent = require("koa-useragent");
const send = require("./send");
const error = require("./error");
const logger = require("koa-logger");
const Interceptor = require("./login.passport");
const bodyParser = require("koa-bodyparser");
const views = require("./views");
const cors = require("koa2-cors");
const static = require("koa-static");
const path = require("path");
module.exports = (app) => {
  app.use(xssmw);
  app.use(userAgent);
  app.use(send);
  app.use(error);
  app.use(logger());
  // 问题：bodyParser底层使用了qs,arrayLimit默认是20,
  // https://segmentfault.com/q/1010000023876312
  // https://www.jianshu.com/p/203d5400b624 qs库的其他限制也需要同步扩展 20230706 thz
  app.use(
    bodyParser({
      formLimit: "2mb",
      queryString: {
        arrayLimit: 100,
        depth: 20, // 参数对象解析深度,设置为20层
        parameterLimit: 2000, // 解析参数数量限制，设置为最大2000个参数
      },
    })
  );
  app.use(Interceptor);
  app.use(static(path.resolve(process.cwd(), "public")));
  views(app);
  app.use(
    cors({
      origin: function (ctx) {
        let result = "";
        const origin = ctx.header.origin;
        const host = ctx.header.host || "";
        if (origin) {
          if (host.indexOf("localhost") != -1 || host.indexOf("jd.com") != -1) {
            result = origin;
          }
        } else if (
          host.indexOf("localhost") != -1 ||
          host.indexOf("jd.com") != -1
        ) {
          result = host;
        }
        return result;
      },
      maxAge: 5, //指定本次预检请求的有效期，单位为秒。
      credentials: true, //是否允许发送Cookie
      allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法
      allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
      exposeHeaders: ["WWW-Authenticate", "Server-Authorization"], //设置获取其他自定
    })
  );
};
